package cn.org.timespace.ons.action.base;

import java.io.PrintWriter;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import cn.org.timespace.easyframe.action.EFBaseAction;
import cn.org.timespace.easyframe.action.EfUserSession;
import cn.org.timespace.easyframe.model.permission.EfUser;
import cn.org.timespace.easyframe.service.permission.EfUserService;
import cn.org.timespace.ons.service.base.MachineTypeNameValueService;
import cn.org.timespace.ons.service.base.OptionsService;
import cn.org.timespace.ons.service.base.UserMachineTypeService;
import cn.org.timespace.ons.util.json.JSONObject;
import cn.org.timespace.ons.util.json.JSONResponseHepler;
import cn.org.timespace.ons.util.pager.Pager;
import cn.org.timespace.ons.util.pager.PagerHelper;
import cn.org.timespace.ons.vo.base.MachineTypeNameValue;
import cn.org.timespace.ons.vo.base.MachinesConf;
import cn.org.timespace.ons.vo.base.Options;
import cn.org.timespace.ons.vo.base.UserMachineType;

import com.opensymphony.xwork2.ActionContext;

public class UserMachineTypeAction extends EFBaseAction {

	private static Log log=LogFactory.getLog(AppleServerAction.class);
	private UserMachineTypeService userMachineTypeService;
	private OptionsService tsOptionsService;
	private MachineTypeNameValueService machineTypeNameValueService;
	
	public MachineTypeNameValueService getMachineTypeNameValueService() {
		return machineTypeNameValueService;
	}
	public void setMachineTypeNameValueService(
			MachineTypeNameValueService machineTypeNameValueService) {
		this.machineTypeNameValueService = machineTypeNameValueService;
	}
	public static Log getLog() {
		return log;
	}
	public static void setLog(Log log) {
		UserMachineTypeAction.log = log;
	}
	public UserMachineTypeService getUserMachineTypeService() {
		return userMachineTypeService;
	}
	public void setUserMachineTypeService(
			UserMachineTypeService userMachineTypeService) {
		this.userMachineTypeService = userMachineTypeService;
	}
	public OptionsService getTsOptionsService() {
		return tsOptionsService;
	}
	public void setTsOptionsService(OptionsService tsOptionsService) {
		this.tsOptionsService = tsOptionsService;
	}
	
	public UserMachineTypeAction(){
		super(new UserMachineTypeModel());
	}
	
	UserMachineTypeModel userMachineTypeModel = (UserMachineTypeModel) this.getModel();
	
	
	/**
	 * 验证类型名称是否存在
	 */
	public String checkName() throws Exception{
		String result = "true"; //存在
		boolean flag=userMachineTypeService.isExistByTypeName(userMachineTypeModel.getName(),getUserAccount());//同一用户下类型名称不可以相同
		if(flag){
			result="true";
		}else{
			result="false";
		}
		getResponse().setCharacterEncoding("UTF-8");
		PrintWriter out = getResponse().getWriter();
		out.write(result);
		return null;
	}
	/**
	 * 增加前先判断是否已经存在，存在执行更新，不存在执行增加
	 * @return
	 * @throws Exception
	 */
	public String doFindById() throws Exception{
		
	String theIdMachine = getRequest().getParameter("theIdMachine") ;
	
	if(!StringUtils.isEmpty(theIdMachine)){  //更新
		UserMachineType userMachineType = userMachineTypeService.findById(theIdMachine);
		userMachineTypeModel.setUserMachineType(userMachineType);
		
		List<MachineTypeNameValue> machineTypeNameValueList = machineTypeNameValueService.findByCondition(theIdMachine);
		getRequest().setAttribute("machineTypeNameValueList", machineTypeNameValueList);
		
		List<Options> list = findByCode();
		Map request = (Map)ActionContext.getContext().get("request");
		request.put("list",list);
		return UPDATE;
	}
	List<Options> list = findByCode();
	Map request = (Map)ActionContext.getContext().get("request");
	request.put("list",list);
	return ADD;
		
	}
	
	/**
	 * 类型下拉列表的选项
	 * @return
	 * @throws Exception
	 */
	public List<Options> findByCode() throws Exception{
		List<Options> list = this.userMachineTypeService.findByCode("machines");
		return list;
	}
	
	/**
	 * 信息平台类型，增加选项
	 * @return
	 * @throws Exception
	 */
	public String doSave() throws Exception{
		UserMachineType userMachineType = userMachineTypeModel.getUserMachineType();
		String userId = getUserAccount();
		userMachineType.setUserId(userId);
		//增加地区码
		String sheng =	userMachineType.getSelA();//省
	    String shi =	userMachineType.getSelB();//市
	    String qu = userMachineType.getSelC();//县/区
	    String id = "";
	    if(qu!=null&&qu.length()>0){
	    	 id = qu;
	    }else if(shi!=null&&shi.length()>0){
	    	
	    	 id = shi;	
	    }else if(sheng!=null&&sheng.length()>0){
	    	 id = sheng;
	    }
	    if(id!=null&&id.length()>0){
	    	if(!userMachineType.getDqM().equals(id)){
	    		userMachineType.setDqM(id);
	    	}
	    }
	    userMachineType.setCreateTime(new Date());
		userMachineTypeService.save(userMachineType);
		
		//保存自定义值
		 String name[] = getRequest().getParameterValues("tname");
		 String value[] = getRequest().getParameterValues("tvalue");
		 String diylength[] = getRequest().getParameterValues("diylength");
		 if(name!=null && name.length>0 ){
				MachineTypeNameValue nameValue = new MachineTypeNameValue();
				
				for(int i=0;i<name.length;i++){
					if("".equals(name[i].toString().trim()) ||"".equals(value[i].toString().trim())){
						continue ;
					}
					
					nameValue.setTheIdMachine(userMachineType.getTheIdMachine());
					nameValue.setName(name[i]);
					nameValue.setValue(value[i]);
					nameValue.setDiylength(Integer.valueOf(diylength[i]));
			    	machineTypeNameValueService.save(nameValue);
			    	//machinesConfService.save(mc);
				}
			}
		 
		
		List<Options> list = findByCode();
		Map request = (Map)ActionContext.getContext().get("request");
		request.put("list",list);
		
		userMachineType.setTheIdMachine("");
		userMachineType.setName("");
		if(userMachineTypeModel.getCodeOne().equals("0")){
			return doList();
		}else if(userMachineTypeModel.getCodeOne().equals("1")){
			return ADD;
		}else{
			return doList();
		}
	}
	
	/**
	 * 信息平台类型列表
	 * @return
	 * @throws Exception
	 */
	 public String doList() throws Exception{
		 Pager p = PagerHelper.getPagerInstance(getRequest());
		 userMachineTypeModel.setUserId(getUserAccount());
			List<Object> resList = userMachineTypeService.findByCondition(userMachineTypeModel,p);
			if(resList != null && resList.size() == 2){
				p.setTotalCount(((Integer)resList.get(0)));
				p.setData((List)resList.get(1));
			}
			List<Options> list = findByCode();
			Map request = (Map)ActionContext.getContext().get("request");
			request.put("list",list);
		 return LIST;
	 }
	 
	 /**
	  * 删除
	  * @return
	  * @throws Exception
	  */
	 public String doDelete() throws Exception{
			String theIdMachine = getRequest().getParameter("theIdMachine");
			
			boolean flag = false;//用于判断是否存在关联，false为存在，不能删除；反之true为不存在，可以删除
			flag = userMachineTypeService.isExistMachineRelation(theIdMachine,getUserAccount());
			if(flag == true){
				//根据Id查找出对应的自定义值
				List<MachineTypeNameValue> list = machineTypeNameValueService.findByCondition(theIdMachine);
				if(list.size()>0){
					for(MachineTypeNameValue nameValue : list){
						machineTypeNameValueService.delete(nameValue);//删除自定义值
					}
				}
			
			UserMachineType userMachineType = userMachineTypeService.findById(theIdMachine);
			userMachineTypeService.delete(userMachineType);
			}else{
				getRequest().setAttribute("isDelete", "No");
			}
			return doList();
		}
	 
	 /**
	  * 更新
	  * @return
	  * @throws Exception
	  */
	 public String doUpdate() throws Exception {
		 
		 
		 getResponse().setContentType("text/html;charset=UTF-8");
		 UserMachineType userMachineType = userMachineTypeModel.getUserMachineType();
		//增加地区码
			String sheng =	userMachineType.getSelA();//省
		    String shi =	userMachineType.getSelB();//市
		    String qu = userMachineType.getSelC();//县/区
		    String dqid = "";
		    if(qu!=null&&qu.length()>0){
		    	dqid = qu;
		    }else if(shi!=null&&shi.length()>0){
		    	
		    	dqid = shi;	
		    }else if(sheng!=null&&sheng.length()>0){
		    	dqid = sheng;
		    }
		    if(dqid!=null&&dqid.length()>0){
		    	if(!userMachineType.getDqM().equals(dqid)){
		    		userMachineType.setDqM(dqid);
		    	}
		    	
		    }
		    userMachineType.setCreateTime(new Date());
		 userMachineTypeService.update(userMachineType);
		 
		 String confNames[] = getRequest().getParameterValues("tname");//自定义名称
		 String confValues[] = getRequest().getParameterValues("tvalue");//自定义值
		 String nvid[] = getRequest().getParameterValues("nvid");//对应machineTypeNameValue表的主键
		 String diylength[] = getRequest().getParameterValues("diylength");
		//自定义名称增减
		 String id = userMachineType.getDeleId();
		 if(id!=null&&id.length()>0){
			 String deleId[] = id.split("-");//自定义名称的id数组
			 for(int i = 0;i<deleId.length ; i++){
					MachineTypeNameValue machineTypeNameValue = machineTypeNameValueService.findById(deleId[i]);
					machineTypeNameValueService.delete(machineTypeNameValue);
				}
		 }
		 
			if(nvid!=null && nvid.length>0){
				MachineTypeNameValue nameValue = new MachineTypeNameValue();
				for(int i = 0; i<nvid.length ; i++){
					if("".equals(confNames[i].toString().trim()) ||"".equals(confNames[i].toString().trim())){
						continue ;
					}
					nameValue = machineTypeNameValueService.findById(nvid[i]);
					nameValue.setName(confNames[i]);
					nameValue.setValue(confValues[i]);
					if(diylength[i]==null||diylength[i]==""){
						nameValue.setDiylength(null);
					}else{
						nameValue.setDiylength(Integer.valueOf(diylength[i]));
					}
					
					machineTypeNameValueService.update(nameValue);
				
				}
				
				
				int nameLen = confNames.length;
				int nvidLen = nvid.length;
				String str = confNames[nvidLen-1];
				//System.out.println(confNames[nameLen-1]);
				if(nameLen>nvidLen && !(str.equals(""))){
					MachineTypeNameValue newMc = new MachineTypeNameValue();
					for(int i = nvidLen ; i<nameLen ; i++){
						if("".equals(confNames[i].toString().trim()) ||"".equals(confNames[i].toString().trim())){
							continue ;
						}
						newMc.setTheIdMachine(userMachineType.getTheIdMachine());
						newMc.setName(confNames[i]);
						newMc.setValue(confValues[i]);
						
						if(diylength.length-i>0&&diylength[i]!=null&&diylength[i].length()>0){
							newMc.setDiylength(Integer.valueOf(diylength[i]));
						}else{
							newMc.setDiylength(null);
						}
//						
						machineTypeNameValueService.save(newMc);
					}
				}	
				
			}else if(confNames!=null && confNames.length>0 && !confNames[0].equals("")){
				MachineTypeNameValue newMc = new MachineTypeNameValue();
				for(int i=0;i<confNames.length;i++){
					if("".equals(confNames[i].toString().trim()) ||"".equals(confNames[i].toString().trim())){
						continue ;
					}
					newMc.setTheIdMachine(userMachineType.getTheIdMachine());
					newMc.setName(confNames[i]);
					newMc.setValue(confValues[i]);
					newMc.setDiylength(Integer.valueOf(diylength[i]));
					machineTypeNameValueService.save(newMc);
				}
			}
			PrintWriter out = getResponse().getWriter();
			out.write("1");
			return null;
		}
	 
	 /**
		 * 校验用户账号是否存在
		 * @return 存在返回 true 不存在返回false
		 * @throws Exception
		 */
		public String doCheckOptionsNameIsExist() throws Exception{
			String result = "true"; //存在
		
			String name = getRequest().getParameter("name");
			UserMachineType userMachineType = userMachineTypeService.doCheckOptionsNameIsExist(getUserAccount(),name);
			if(userMachineType == null){
				result = "false"; //不存在
			}
			
			getResponse().setCharacterEncoding("UTF-8");
			PrintWriter out = getResponse().getWriter();
			out.write(result);
			
			return null;
		}
		
		 /**
		  * 列出我的终端应用类型
		  * @return
		  * @throws Exception
		  */
		 public String doMyMachineTypeList() throws Exception{
			 Pager p = PagerHelper.getPagerInstance(getRequest());
			 userMachineTypeModel.setUserId(getUserAccount());
				List<Object> resList = userMachineTypeService.findByCondition(userMachineTypeModel,p);
				if(resList != null && resList.size() == 2){
					p.setTotalCount(((Integer)resList.get(0)));
					p.setData((List)resList.get(1));
				}
				List<Options> list = findByCode();
				Map request = (Map)ActionContext.getContext().get("request");
				request.put("list",list);
				String idandusername = getRequest().getParameter("nid");
				//getRequest().setAttribute(idandusername, idandusername);
				getRequest().setAttribute("idname", idandusername);
			 return "listtype";
		 }
		 
		 /**
		  * 列出我的终端应用类型,不列出已选择的应用类型
		  * @return
		  * @throws Exception
		  */
		 public String doMyMachineAppTypeList() throws Exception{
			 Pager p = PagerHelper.getPagerInstance(getRequest());
			 userMachineTypeModel.setUserId(getUserAccount());
			 String idandusername = getRequest().getParameter("nid");
			 String theidname[] = idandusername.split("-");
				List<Object> resList = userMachineTypeService.findAppByCondition(userMachineTypeModel,p,theidname[0]);
				if(resList != null && resList.size() == 2){
					p.setTotalCount(((Integer)resList.get(0)));
					p.setData((List)resList.get(1));
				}
				List<Options> list = findByCode();
				Map request = (Map)ActionContext.getContext().get("request");
				request.put("list",list);
				
				//getRequest().setAttribute(idandusername, idandusername);
				getRequest().setAttribute("idname", idandusername);
			 return "listtype";
		 }
}
